import IndexedDB from "./indexHelper";
import { reactive } from "vue";
/*
     把 indexedDB 的help 做成插件的形式
*/
export default {
  _indexedDBFlag: Symbol("mstart-db-help"),
  _help: {}, // 访问数据库的实例
  _store: {}, // 存放对象，实现 foo.addModel(obj)的功能

  createHelp(info) {
    let indexedDBFlag = this._indexedDBFlag;
    if (typeof info.dbFlag === "string") {
      indexedDBFlag = Symbol.for(info.dbFlag);
    } else if (typeof info.dbFlag === "symbol") {
      indexedDBFlag = info.dbFlag;
    }

    // 链接数据库，获得实例
    const help = new IndexedDB(info);

    // 存入静态对象，以便支持多个不同的实例
    this._help[indexedDBFlag] = help; //实例
    this._store[indexedDBFlag] = {}; //仓库

    // 把仓库变成对象的形式，避免写字符串房形式的仓库名
    for (const key in info.stores) {
      this._store[indexedDBFlag][key] = {
        createModel: (model) => {
          class MyModel {
            constructor(_model) {
              for (const key in _model) {
                this[key] = _model[key];
              }
            }
            add(tran = null) {
              return help.addModel(key, this, tran);
            }
            save(tran = null) {
              const _id = this[info.stores[key].id];
              return help.setModel(key, this, _id, tran);
            }
            load(tran = null) {
              return new Promise((resolve, reject) => {
                // 套个娃
                const _id = this[info.stores[key].id];
                help.getModel(key, _id, tran).then((res) => {
                  Object.assign(this, res);
                  resolve(res);
                });
              });
            }
            del(tran = null) {
              const _id = this[info.stores[key].id];
              return help.delModel(key, _id, tran);
            }
          }
          const re = new MyModel(model);
          return reactive(re);
        },
        // put: (obj) => {
        //   let _id = obj;
        //   if (typeof obj === "object") {
        //     _id = obj[info.stores[key].id];
        //   }
        //   return help.putModel(key, obj, _id);
        // },
        // del: (obj) => {
        //   let _id = obj;
        //   if (typeof obj === "object") {
        //     _id = obj[info.stores[key].id];
        //   }
        //   return help.delModel(key, _id);
        // },
        // add: (obj) => help.addModel(key, obj),
        // get: (id = null) => help.addModel(key, id),
      };
    }
  },

  // 获取静态对象里的数据库实例
  useDBHelp(_dbFlag) {
    let flag = this._indexedDBFlag;
    if (typeof _dbFlag === "string") {
      flag = Symbol.for(_dbFlag);
    } else if (typeof _dbFlag === "symbol") {
      flag = _dbFlag;
    }
  },
  useStore(_dbFlag) {
    let flag = this._indexedDBFlag;
    if (typeof _dbFlag === "string") {
      flag = Symbol.for(_dbFlag);
    } else if (typeof _dbFlag === "symbol") {
      flag = _dbFlag;
    }
    return this._store[flag];
  },
};
